﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Assist;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Electrical;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YArchitech.Revit;
using YArchitech.Revit.Electric.Common;

namespace HYRElectric.Dimension
{
	[Regeneration(RegenerationOption.Manual)]
	[Transaction(TransactionMode.Manual)]
	public class CmdEquipmentDim : YJKCommandManual
	{
		protected override Result YJKExcute(ExternalCommandData cmdData, ref string message, ElementSet elements)
		{
			if (this.m_lstElecTagType.Count == 0)
			{
				return Autodesk.Revit.UI.Result.Cancelled;
			}
			this.m_doc = cmdData.Application.ActiveUIDocument.Document;
            System.Windows.Forms.Form form = null;
			if (this.m_dlgText == "桥架标注")
			{
				form = new DlgLeadEquipmentDim(cmdData.Application, this.m_lstElecTagType, this.m_dlgText);
			}
			else
			{
				form = new DlgEquipmentDim(cmdData.Application, this.m_lstElecTagType, this.m_dlgText);
			}
			form.Show(WindowHelper.HWndRevit);
			WindowHelper.SendMessageToWndRevit();
			ISelectionFilter selectionFilter;
			if (!this.CreateSelectionFilter(out selectionFilter))
			{
				return Autodesk.Revit.UI.Result.Cancelled;
			}
			Result result;
			for (;;)
			{
				try
				{
					Selection selection = cmdData.Application.ActiveUIDocument.Selection;
					Reference reference = selection.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element, selectionFilter, this.m_prompt);
					if (reference != null)
					{
						Element elementById = this.m_doc.GetElementById(reference.ElementId);
						Family family;
						if (this.m_dlgText == "桥架标注")
						{
							family = ((DlgLeadEquipmentDim)form).SelectDbFamily.Load(this.m_doc);
						}
						else
						{
							family = ((DlgEquipmentDim)form).SelectDbFamily.Load(this.m_doc);
						}
						if (family == null)
						{
							form.Close();
							result = Autodesk.Revit.UI.Result.Cancelled;
							break;
						}
						FamilySymbol familySymbol = null;
						foreach (FamilySymbol familySymbol2 in family.GetSymbols())
						{
							if (familySymbol2 != null)
							{
								familySymbol = familySymbol2;
								break;
							}
						}
						if (familySymbol == null || familySymbol.Id == null)
						{
							form.Close();
							result = Autodesk.Revit.UI.Result.Cancelled;
							break;
						}
						this.StartTransaction();
						this.DeleteEquipmentTag(elementById);
						XYZ xyz = selection.PickPoint("请点选标注位置");
						if (this.m_dlgText == "桥架标注")
						{
							this.AddEquipmentShareParam(cmdData.Application.ActiveUIDocument.Document, elementById);
							WireDimension.DeleteLeadLineGroups(this.m_doc, elementById, "桥架标记引线ID");
							if (((DlgLeadEquipmentDim)form).chkLeadDim.Checked)
							{
								this.CreateEquipmentTag(cmdData.Application.ActiveUIDocument, reference, xyz, familySymbol);
							}
							else
							{
								this.m_uiDoc.Document.Create.NewTag(this.m_uiDoc.ActiveView, elementById, false, 0, 0, xyz).ChangeTypeId(familySymbol.Id);
							}
						}
						else
						{
							this.m_uiDoc.Document.Create.NewTag(this.m_uiDoc.ActiveView, elementById, false, 0, 0, xyz).ChangeTypeId(familySymbol.Id);
						}
						this.CommitTransaction();
					}
					continue;
				}
				catch (Exception)
				{
					this.RollbackTransaction();
					form.Close();
					result = Autodesk.Revit.UI.Result.Succeeded;
				}
				break;
			}
			return result;
		}

		private void CreateEquipmentTag(UIDocument uiDoc, Reference refer, XYZ pickPoint, FamilySymbol fs)
		{
			Document document = uiDoc.Document;
            Autodesk.Revit.DB.View activeView = document.ActiveView;
			XYZ xyz = new XYZ(1.0, 0.0, 0.0);
			XYZ globalPoint = refer.GlobalPoint;
			Element element = uiDoc.Document.GetElement(refer);
			pickPoint = new XYZ(pickPoint.X, pickPoint.Y, globalPoint.Z);
			IndependentTag independentTag = document.Create.NewTag(activeView, element as CableTray, false, 0, 0, pickPoint);
			independentTag.ChangeTypeId(fs.Id);
			this.CommitTransaction();
			Family family = fs.Family;
			Document document2 = document.EditFamily(family);
			if (document2 == null || !document2.IsFamilyDocument)
			{
				MessageBox.Show("it's family document");
				return;
			}
			Curve curve = ((new FilteredElementCollector(document2).OfClass(typeof(CurveElement)).ToElements()[0] as DetailLine).Location as LocationCurve).Curve;
			this.StartTransaction();
			if (pickPoint.X < globalPoint.X)
			{
				xyz = new XYZ(-1.0, 0.0, 0.0);
			}
			double num = curve.Length * (double)document.ActiveView.Scale;
			ElementId elementId = WireDimension.CreatLeadLine(uiDoc, element, globalPoint, pickPoint, xyz, num, false);
			XYZ xyz2 = (pickPoint + (pickPoint + num * xyz)) / 2.0;
			ElementTransformUtils.MoveElement(document, independentTag.Id, xyz2 - pickPoint);
			element.GetParameter("桥架标记引线ID").Set(elementId.ToString());
		}

		private void AddEquipmentShareParam(Document doc, Element wire)
		{
			Dictionary<string, ParameterType> dictionary = new Dictionary<string, ParameterType>();
            dictionary.Add("桥架标记引线ID", (ParameterType)1);
			foreach (KeyValuePair<string, ParameterType> keyValuePair in dictionary)
			{
				if (wire.GetParameter(keyValuePair.Key) == null)
				{
					YArchitech.Revit.Electric.Common.SharedParameter.InsertSharedParameter(doc, BuiltInCategory.OST_CableTray, "电气数据", dictionary, false);
					break;
				}
			}
		}

		private void StartTransaction()
		{
			this.m_trans = new Transaction(this.m_doc, this.m_dlgText);
			this.m_trans.Start();
		}

		private void CommitTransaction()
		{
			if (this.m_trans != null)
			{
				this.m_trans.Commit();
			}
		}

		private void RollbackTransaction()
		{
            if (this.m_trans != null && this.m_trans.GetStatus() == (TransactionStatus)1)
			{
				this.m_trans.RollBack();
			}
		}

		private bool CreateSelectionFilter(out ISelectionFilter filter)
		{
			filter = null;
			string eCategoryName = this.m_eCategoryName;
			uint num = 0;//<PrivateImplementationDetails>.ComputeStringHash(eCategoryName);
			if (num <= 2153660493u)
			{
				if (num != 552892363u)
				{
					if (num != 1943268065u)
					{
						if (num == 2153660493u)
						{
							if (eCategoryName == "动力开关")
							{
								filter = new RevitFilter.PowerSwitchFilter(this.m_doc);
							}
						}
					}
					else if (eCategoryName == "照明开关")
					{
						filter = new LightingSwitchFilter();
					}
				}
				else if (eCategoryName == "灯具")
				{
					filter = new LightFilter();
				}
			}
			else if (num <= 2291516886u)
			{
				if (num != 2210146450u)
				{
					if (num == 2291516886u)
					{
						if (eCategoryName == "插座")
						{
							filter = new RevitFilter.SocketFilter(this.m_doc);
						}
					}
				}
				else if (eCategoryName == "配电箱")
				{
					filter = new ElectricEquipmentFilter();
				}
			}
			else if (num != 3815063138u)
			{
				if (num == 4150015308u)
				{
					if (eCategoryName == "导线")
					{
                        filter = new ElectricDim.WireFilter();
					}
				}
			}
			else if (eCategoryName == "桥架")
			{
				filter = new CableTrayFilter();
			}
			return filter != null;
		}

		private bool DeleteEquipmentTag(Element element)
		{
			List<Element> equipmentTag = this.GetEquipmentTag(element);
			if (equipmentTag == null || equipmentTag.Count == 0)
			{
				return false;
			}
			foreach (Element element2 in equipmentTag)
			{
				this.m_doc.Delete(element2.Id);
			}
			this.m_doc.Regenerate();
			return true;
		}

		private List<Element> GetEquipmentTag(Element element)
		{
			if (element == null)
			{
				return null;
			}
			List<string> list = new List<string>();
			string eCategoryName = this.m_eCategoryName;
			uint num = 0;//<PrivateImplementationDetails>.ComputeStringHash(eCategoryName);
			BuiltInCategory category;
			if (num <= 2153660493u)
			{
				if (num != 552892363u)
				{
					if (num != 1943268065u)
					{
						if (num == 2153660493u)
						{
							if (eCategoryName == "动力开关")
							{
								category = BuiltInCategory.OST_LightingDeviceTags;
								list.Add("开关标记");
								goto IL_17B;
							}
						}
					}
					else if (eCategoryName == "照明开关")
					{
						category = BuiltInCategory.OST_LightingDeviceTags;
						list.Add("开关标记");
						goto IL_17B;
					}
				}
				else if (eCategoryName == "灯具")
				{
					category = BuiltInCategory.OST_LightingFixtureTags;
					list.Add("灯具标记");
					goto IL_17B;
				}
			}
			else if (num <= 2291516886u)
			{
				if (num != 2210146450u)
				{
					if (num == 2291516886u)
					{
						if (eCategoryName == "插座")
						{
							category = BuiltInCategory.OST_ElectricalFixtureTags;
							list.Add("插座标记");
							goto IL_17B;
						}
					}
				}
				else if (eCategoryName == "配电箱")
				{
					category = BuiltInCategory.OST_ElectricalEquipmentTags;
					list.Add("箱柜标记");
					goto IL_17B;
				}
			}
			else if (num != 3815063138u)
			{
				if (num == 4150015308u)
				{
					if (eCategoryName == "导线")
					{
						category = BuiltInCategory.OST_WireTags;
						list.Add("导线标记");
						goto IL_17B;
					}
				}
			}
			else if (eCategoryName == "桥架")
			{
				category = BuiltInCategory.OST_CableTrayTags;
				list.Add("桥架标记");
				goto IL_17B;
			}
			return null;
			IL_17B:
			return DimensionUtil.ElementTags(this.m_doc, element, category, list);
		}

		protected string m_eCategoryName = "灯具";

		protected List<string> m_lstElecTagType = new List<string>();

		protected string m_dlgText = "";

		protected string m_prompt = "设备标注";

		private Transaction m_trans;
	}
}
